package org.github.manx98.jlibhac.hle;

import org.github.manx98.jlibhac.fs.IStorage;
import org.github.manx98.jlibhac.util.StringUtil;

import java.io.IOException;

/**
 * @author Manx98
 * @version 1.0
 * @since 2022/10/5 23:48
 */
public class Npdm {
    private static final int MetaMagic = 'M' | 'E' << 8 | 'T' << 16 | 'A' << 24;
    public byte ProcessFlags;
    public boolean Is64Bit;
    public byte MainThreadPriority;
    public byte DefaultCpuId;
    public int PersonalMmHeapSize;
    public int Version;
    public int MainThreadStackSize;
    public String TitleName;
    public byte[] ProductCode;
    public Aci0 Aci0;
    public Acid Acid;


    public Npdm(IStorage reader) throws IOException {

        if (reader.readInt() != MetaMagic)
        {
            throw new IllegalArgumentException("NPDM Stream doesn't contain NPDM file!");
        }

        reader.readLong();

        ProcessFlags = reader.readByte();

        Is64Bit = (ProcessFlags & 1) != 0;

        reader.readByte();

        MainThreadPriority = reader.readByte();
        DefaultCpuId       = reader.readByte();

        reader.readInt();

        PersonalMmHeapSize = reader.readInt();

        Version = reader.readInt();

        MainThreadStackSize = reader.readInt();

        byte[] tempTitleName = reader.readBytes(0x10);

        TitleName = StringUtil.utf8ZToString(tempTitleName,0, tempTitleName.length);

        ProductCode = reader.readBytes(0x10);

        reader.setPosition(reader.getPosition() + 0x30);

        int aci0Offset = reader.readInt();
        int aci0Size   = reader.readInt();
        int acidOffset = reader.readInt();
        int acidSize   = reader.readInt();

        Aci0 = new Aci0(reader, aci0Offset);
        Acid = new Acid(reader, acidOffset);
    }
}
